<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use DB;
use Request;

class DBAPIController extends Controller
{
    protected $canLockedModel = ['ExpertGroup', 'AwardGroup'];

    public function __construct()
    {
        $this->middleware(['auth', 'admin'], [
            'except' => []
        ]);
    }

    public function get()
    {
        $data = Request::all();
        isset($data['model']) or die('No `model`');
        $modelClass = 'App\\' . $data['model'];
        $query = $modelClass::whereRaw('1=1');
        if (isset($data['select'])) {
            $query->select($data['select']);
        }
        if (isset($data['where'])) {
            foreach ($data['where'] as $where) {
                if (count($where) == 2) {
                    $query->where($where[0], $where[1]);
                } elseif (count($where) == 3) {
                    $query->where($where[0], $where[1], $where[2]);
                }
            }
        }
        if (isset($data['order'])) {
            $query->orderBy($data['order'][0], isset($data['order'][1]) ? $data['order'][1] : 'asc');
        }
        if (isset($data['limit'])) {
            $query->take($data['limit']);
        }
        $rows = $query->get();
        return $this->json($rows);
    }

    public function create()
    {
        $data = Request::all();
        isset($data['model']) or die('No `model`');
        isset($data['records']) or die('No `records`');
        is_array($data['records']) or die('`records` is not an array');
        !empty($data['records']) or die('`records` is empty');
        $modelClass = 'App\\' . $data['model'];
        $records = $data['records'];
        $uniqueFields = isset($data['unique']) ? $data['unique'] : [];
        if (!empty($uniqueFields)) {
            foreach ($uniqueFields as $uniqueField) {
                $values = array_map(function ($item) use ($uniqueField) {
                    return $item[$uniqueField['field_name']];
                }, $records);
                $existingRowCount = $modelClass::whereIn($uniqueField['field_name'], $values)->count();
                if ($existingRowCount) {
                    $result = ['ok' => false, 'message' => $uniqueField['error_message']];
                    return $this->json($result);
                }
            }
        }
        $rowIds = [];
        foreach ($records as $record) {
            $row = $modelClass::create($record);
            $rowIds[] = $row->id;
        }
        $result = ['ok' => true, 'row_ids' => $rowIds];
        return $this->json($result);
    }

    public function update()
    {
        $data = Request::all();
        isset($data['model']) or die('No `model`');
        isset($data['records']) or die('No `records`');
        is_array($data['records']) or die('`records` is not an array');
        !empty($data['records']) or die('`records` is empty');
        $modelClass = 'App\\' . $data['model'];
        $records = $data['records'];
        foreach ($records as $record) {
            if (empty($record['id'])) {
                $result = ['ok' => false, 'message' => "record `id` 为空"];
                return $this->json($result);
            }
        }
        foreach ($records as $record) {
            $row = $modelClass::find($record['id']);
            $uniqueFields = isset($data['unique']) ? $data['unique'] : [];
            if (!empty($uniqueFields)) {
                foreach ($uniqueFields as $uniqueField) {
                    $existingRowCount = $modelClass::where('id', '<>', $record['id'])->where($uniqueField['field_name'], $record[$uniqueField['field_name']])->count();
                    if ($existingRowCount) {
                        $result = ['ok' => false, 'message' => $uniqueField['error_message']];
                        return $this->json($result);
                    }
                }
            }
            //项目组和专家组锁定后不可修改
            if (isset($data['check_locked']) && in_array($data['model'], $this->canLockedModel) && $row->isLocked()) {
                $result = ['ok' => false, 'message' => '该分组已锁定，不可修改'];
                return $this->json($result);
            }
            $row->update($record);
        }
        $result = ['ok' => true];
        return $this->json($result);
    }

    public function delete()
    {
        $data = Request::all();
        isset($data['model']) or die('No `model`');
        isset($data['record_ids']) or die('No `record_ids`');
        is_array($data['record_ids']) or die('`record_ids` is not an array');
        !empty($data['record_ids']) or die('`record_ids` is empty');
        $modelClass = 'App\\' . $data['model'];
        $recordIds = $data['record_ids'];
        $modelClass::destroy($recordIds);
        $result = ['ok' => true];
        return $this->json($result);
    }
}
